#include "EPD_Fun.h"
#include "EPD_init.h"
//#include "EPD_Photo.h"

uint8_t GRAM[5000] = {0x00};

void EPD_Display(void)
{
	 
	EPD_Write(Cmd,0x22);
<<<<<<< Updated upstream
	EPD_Write(Data,0xCF); 

=======
	EPD_Write(Data,0x99);
	
	EPD_Write(Cmd,0x20);
	EPD_WaitBusy();
	
	EPD_Write(Cmd,0x22);
	EPD_Write(Data,0xFF); 
	
>>>>>>> Stashed changes
	EPD_Write(Cmd,0x20);
	EPD_WaitBusy();
}

void EPD_Update(void)
{
	uint16_t i = 0;
	EPD_Write(Cmd,0x24);
    for(i=0;i<5000;i++)
    {               
        EPD_Write(Data,GRAM[i]);
    }
	
    EPD_Write(Cmd,0x26);;
    for(i=0;i<5000;i++)
    {               
        EPD_Write(Data,GRAM[i]);
    }
}
void EPD_SetPixel(uint16_t x,uint16_t y,ColorTypeDef Color)
{
	uint16_t addr = 0;
	uint16_t X = 0;
	uint16_t Y = 0;
	
#if ROTATE_0
	X = x;
	Y = y;
#endif
	
#if ROTATE_90
	X = y;
	Y = Height-x-1;
#endif
	
#if ROTATE_180
	X = Width-x-1;
	Y = Height-y-1;
#endif
	
#if ROTATE_270
	X = Width-y-1;
	Y = x;
#endif
	addr = X / 8 + Y * (Width / 8);
	if(Color == BLACK)
	{
		GRAM[addr] &= ~(0x80 >> (X % 8));
	}
	else
	{
		GRAM[addr] |= (0x80 >> (X % 8));
	}
}

void EPD_Clear(ColorTypeDef Color)
{
    unsigned int i,j;
	for(i=0;i<200;i++)
	{
		for(j=0;j<200;j++)
		{
			EPD_SetPixel(j,i,Color);
		}
	}
}

void EPD_DrawPoint(uint16_t x,uint16_t y,ColorTypeDef Color)
{
	EPD_SetPixel(x-1,y-1,Color);
}

uint8_t Abs(uint8_t x,uint8_t y)
{
	return (x < y) ? (y - x) : (x - y);
}


void EPD_DrawLine(uint8_t Xstart,uint8_t Ystart,uint8_t Xend,uint8_t Yend,uint8_t n,ColorTypeDef Color)
{
	float X,Y;
	signed short dX,dY;
	uint8_t lm;
	uint8_t i;
	
	X = Xstart + 0.5f;
	Y = Ystart + 0.5f;
	
	if((Xstart != Xend) && (Ystart != Yend))
	{
		lm = (Abs(Xstart,Xend) < Abs(Ystart,Yend)) ? Abs(Ystart,Yend) :Abs(Xstart,Xend);
		dX = (Xend - Xstart) / lm;
		dY = (Yend - Ystart) / lm;
	}
	else if((Xstart != Xend) && (Ystart == Yend))
	{
		lm = Abs(Xstart,Xend);
		dX = (Xend - Xstart) / lm;
		dY = 0;
	}
	else if((Xstart == Xend) && (Ystart != Yend))
	{
		lm = Abs(Ystart,Yend);
		dX = 0;
		dY = (Yend - Ystart) / lm;
	}
	else
	{
		lm = 0;
		dX = 0;
		dY = 0;
	}
	
	for(i = 0; i <= lm; i++)
	{
		if(i % n == 0)
		{
			EPD_DrawPoint((uint16_t)X,(uint16_t)Y,Color);
		}
		X += dX;
		Y += dY;
	}
}

void EPD_DrawCircle(uint8_t X,uint8_t Y,uint16_t radius,ColorTypeDef Color)
{
	
}

void EPD_ShowPicture(uint16_t X,uint16_t Y,const uint8_t * Pic,uint16_t width,uint16_t heigth)
{
	uint8_t i,j;
	uint8_t WidthByte;
	uint16_t Addr;
	WidthByte = ((width % 8) == 0) ? (width / 8) : (width / 8 +1);
	
	for(i = 0; i < heigth; i++)
	{
		for(j = 0; j < width; j++)
		{
			Addr = j / 8 + i * WidthByte;
			if((Pic[Addr] & (0x80 >> (j % 8))) == 0)
			{
				EPD_DrawPoint(j + X,i + Y,WHITE);
			}
			else
			{
				EPD_DrawPoint(j + X,i + Y,BLACK);
			}
		}
	}
}


